package com.mine.protocol;

import com.mine.common.Invocation;
import com.mine.register.LocalServiceRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author weixiao
 * @date 2025/3/31 10:53
 */
public class HttpServerHandler {

    public void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 解析参数
            Invocation invocation = (Invocation) new ObjectInputStream(req.getInputStream()).readObject();
            Class implClass = LocalServiceRegister.get(invocation.getInterfaceName(), "1.0");
            Method method = implClass.getMethod(invocation.getMethodName(), invocation.getParameterTypes());
            // 处理请求
            String result = (String) method.invoke(implClass.newInstance(), invocation.getParameters());
            // 返回响应
            IOUtils.write(result, resp.getOutputStream());
        } catch (IOException | ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}
